<?php
// +----------------------------------------------------------------------
// | 海豚PHP框架 [ DolphinPHP ]
// +----------------------------------------------------------------------
// | 版权所有 2016~2019 广东卓锐软件有限公司 [ http://www.zrthink.com ]
// +----------------------------------------------------------------------
// | 官方网站: http://dolphinphp.com
// +----------------------------------------------------------------------

namespace app\admin\controller;

use app\common\builder\ZBuilder;
use app\user\model\User as UserModel;
use think\Db;
use think\facade\Cache;
use think\facade\Env;
use app\web\model\User;
use app\web\model\Technician;
use app\web\model\Shop;
use app\web\model\Order;


/**
 * 后台默认控制器
 * @package app\admin\controller
 */
class Index extends Admin {
	/**
	 * 后台首页
	 * @author 蔡伟明 <314013107@qq.com>
	 * @return string
	 */
	public function index() {

		$user = UserModel::get(session("user_auth.uid"))->toArray();
		if (session("last_login_time")) {
			$user['last_login_time'] = session('last_login_time');
			$user['last_login_ip'] = session('last_login_ip');
		}
		$this->assign("user", $user);
		//用户总数
		$this->assign('user_total',User::where([['nickName','<>','']])->count());
		//入住技术数量
		$this->assign('t_total',Technician::where([['is_sub','=',1],['check_status','=',1]])->count());
		//待审核技师
		$this->assign('t_total1',Technician::where([['is_sub','=',1],['check_status','=',0]])->count());
		//入住商家数量
		$this->assign('s_total',Shop::where([['is_sub','=',1],['check_status','=',1]])->count());
		//待审核商家数量
		$this->assign('s_total1',Shop::where([['is_sub','=',1],['check_status','=',0]])->count());

		$this->assign('commission_tot',$this->getTotCommission());

		// return $this->fetch();
		return view("/index/analysis");
	}

	private function getTotCommission()
	{
		$tot = Order::where(['status'=>4])->sum('platform_commission');
		return $tot;
	}





	/**
	 * 清空系统缓存
	 * @author 蔡伟明 <314013107@qq.com>
	 */
	public function wipeCache() {
		$wipe_cache_type = config('wipe_cache_type');
		if (!empty($wipe_cache_type)) {
			foreach ($wipe_cache_type as $item) {
				switch ($item) {
				case 'TEMP_PATH':
					array_map('unlink', glob(Env::get('runtime_path') . 'temp/*.*'));
					break;
				case 'LOG_PATH':
					$dirs = (array) glob(Env::get('runtime_path') . 'log/*');
					foreach ($dirs as $dir) {
						array_map('unlink', glob($dir . '/*.log'));
					}
					array_map('rmdir', $dirs);
					break;
				case 'CACHE_PATH':
					array_map('unlink', glob(Env::get('runtime_path') . 'cache/*.*'));
					break;
				}
			}
			Cache::clear();
			$this->success('清空成功');
		} else {
			$this->error('请在系统设置中选择需要清除的缓存类型');
		}
	}

	/**
	 * 个人设置
	 * @author 蔡伟明 <314013107@qq.com>
	 */
	public function profile() {
		// 保存数据
		if ($this->request->isPost()) {
			$data = $this->request->post();

			$data['nickname'] == '' && $this->error('昵称不能为空');
			$data['id'] = UID;

			// 如果没有填写密码，则不更新密码
			if ($data['password'] == '') {
				unset($data['password']);
			} else {
				$data['password'] = ($data['password']);
			}

			$UserModel = new UserModel();
			if ($user = $UserModel->allowField(['nickname', 'email', 'password', 'mobile', 'avatar'])->update($data)) {
				// 记录行为
				action_log('user_edit', 'admin_user', UID, UID, get_nickname(UID));
				$this->success('编辑成功');
			} else {
				$this->error('编辑失败');
			}
		}

		// 获取数据
		$info = UserModel::where('id', UID)->field('password', true)->find();

		// 使用ZBuilder快速创建表单
		return ZBuilder::make('form')
			->addFormItems([ // 批量添加表单项
				['static', 'username', '用户名', '不可更改'],
				['text', 'nickname', '昵称', '可以是中文'],
				['text', 'email', '邮箱', ''],
				['password', 'password', '密码', '必填，6-20位'],
				['text', 'mobile', '手机号'],
				['image', 'avatar', '头像'],
			])
			->setFormData($info) // 设置表单数据
			->fetch();
	}

	/**
	 * 检查版本更新
	 * @author 蔡伟明 <314013107@qq.com>
	 * @return \think\response\Json
	 * @throws \think\db\exception\BindParamException
	 * @throws \think\exception\PDOException
	 */
	public function checkUpdate() {
		$params = config('dolphin.');
		$params['domain'] = request()->domain();
		$params['website'] = config('web_site_title');
		$params['ip'] = $_SERVER['SERVER_ADDR'];
		$params['php_os'] = PHP_OS;
		$params['php_version'] = PHP_VERSION;
		$params['mysql_version'] = db()->query('select version() as version')[0]['version'];
		$params['server_software'] = $_SERVER['SERVER_SOFTWARE'];
		$params = http_build_query($params);

		$opts = [
			CURLOPT_TIMEOUT => 20,
			CURLOPT_RETURNTRANSFER => true,
			CURLOPT_URL => config('dolphin.product_update'),
			CURLOPT_USERAGENT => $_SERVER['HTTP_USER_AGENT'],
			CURLOPT_POST => 1,
			CURLOPT_POSTFIELDS => $params,
		];

		// 初始化并执行curl请求
		$ch = curl_init();
		curl_setopt_array($ch, $opts);
		$data = curl_exec($ch);
		curl_close($ch);

		$result = json_decode($data, true);

		if ($result['code'] == 1) {
			return json([
				'update' => '<a class="badge badge-primary" href="http://www.dolphinphp.com/download" target="_blank">有新版本：' . $result["version"] . '</a>',
				'auth' => $result['auth'],
			]);
		} else {
			return json([
				'update' => '',
				'auth' => $result['auth'],
			]);
		}
	}
}